package com.invite.me.ui.cehualan;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.invite.me.R;
import com.invite.me.base.BaseActivity;
import com.invite.me.beans.fabean.ShimingRzCBean;
import com.invite.me.beans.presenter.NameAttestationPresenter;
import com.invite.me.beans.res.NameAtteastationtpBean;
import com.invite.me.beans.res.NameattestationBean;
import com.invite.me.util.RegularUtil;
import com.invite.me.util.ToastUtils;
import com.invite.me.wlqq.Constants;
import com.invite.me.wlqq.Contract;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class NameAttestationActivity extends BaseActivity implements View.OnClickListener, Contract.BaseView{

    private EditText shuruxingming;
    private EditText shurushenfenzhenghao;
    private ImageView zhengmian;
    private ImageView fanmian;
    private boolean tupianzhuangtai=true;
    private TextView shangchuan;
    private List<LocalMedia> selectList = new ArrayList<>();
    NameAttestationPresenter nameAttestationPresenter;
    private LinearLayout yijingrenzheng;
    private ScrollView scrollview;

    private String zhaopianzhengmian;
    private String zhaopianfanmian;
    private boolean zhemiantype=true;
    private boolean fanmiantype=true;
    private TextView shenfenhao;
    private TextView mingzi;


    @Override
    protected void initView() {
        nameAttestationPresenter= new NameAttestationPresenter(this);
        nameAttestationPresenter.shilie();
        ImageView imagefanhui= findViewById(R.id.imagefanhui);
        shenfenhao = findViewById(R.id.shenfenhao);
        mingzi = findViewById(R.id.mingzi);

        shuruxingming = findViewById(R.id.shuruxingming);
        yijingrenzheng = findViewById(R.id.yijingrenzheng);
        scrollview = findViewById(R.id.scrollview);
        shurushenfenzhenghao = findViewById(R.id.shurushenfenzhenghao);
        zhengmian = findViewById(R.id.zhengmian);
        fanmian = findViewById(R.id.fanmian);
        TextView shangchuan = findViewById(R.id.shangchuan);

        imagefanhui.setOnClickListener(this);
        zhengmian.setOnClickListener(this);
        fanmian.setOnClickListener(this);
        shangchuan.setOnClickListener(this);

        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(NameAttestationActivity.this);
                }
                else {
                    Toast.makeText(NameAttestationActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });


    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.imagefanhui:
                finish();
                break;
            case R.id.shangchuan:
                String xingming = shuruxingming.getText().toString();
                String shenfen = shurushenfenzhenghao.getText().toString();

                if(!RegularUtil.isLegalName(xingming)){
                    Toast.makeText(this, "请输入真实姓名", Toast.LENGTH_SHORT).show();
                    return;
                } else if(!RegularUtil.personIdValidation(shenfen)){
                    Toast.makeText(this, "请输入合理的身份证号", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(zhaopianzhengmian)){
                    Toast.makeText(this, "请上传人像正面", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(zhaopianfanmian)){
                    Toast.makeText(this, "请上传国徽面", Toast.LENGTH_SHORT).show();
                    return;
                }
                nameAttestationPresenter.tijiaoshimingrenzheng(xingming,shenfen,zhaopianzhengmian,zhaopianfanmian);


                break;
            case R.id.zhengmian:
                if(tupianzhuangtai){
                    tupianzhuangtai=false;
                    zhemiantype=true;
                    fanmiantype=false;
                    gerxiangce();
                }


                break;
            case R.id.fanmian:
                if(tupianzhuangtai){
                    tupianzhuangtai=false;
                    zhemiantype=false;
                    fanmiantype=true;
                    gerxiangce();
                }
                break;

        }

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected int getActivityLayoutId() {
        return R.layout.activity_nameattestation;
    }

    @Override
    protected void loadData() {

    }

    //相册
    private void gerxiangce() {
        PictureSelector.create(NameAttestationActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                //   .theme(R.style.)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(9)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                //  .previewVideo(cb_preview_video.isChecked())// 是否可预览视频
                //   .enablePreviewAudio(cb_preview_audio.isChecked()) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                //  .enableCrop(true)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                //.compressSavePath(getPath())//压缩图片保存地址
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                // .isGif(cb_isGif.isChecked())// 是否显示gif图片
                //  .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                //  .circleDimmedLayer(cb_crop_circular.isChecked())// 是否圆形裁剪
                //  .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                //.showCropGrid(cb_showCropGrid.isChecked())// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(true)// 是否开启点击声音
                //  .selectionMedia(selectList)// 是否传入已选图片
                //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                .minimumCompressSize(50)// 小于100kb的图片不压缩
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                //.rotateEnabled(true) // 裁剪是否可旋转图片
                //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                //.videoQuality()// 视频录制质量 0 or 1
                //.videoSecond()//显示多少秒以内的视频or音频也可适用
                //.recordVideoSecond()//录制视频秒数 默认60s
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                selectList = PictureSelector.obtainMultipleResult(data);
                String path = "";

                for (int i = 0; i < selectList.size(); i++) {
                    LocalMedia media = selectList.get(i);
                    if (media.isCut() && !media.isCompressed()) {
                        // 裁剪过
                        path = media.getCutPath();
                    } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                        // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                        path = media.getCompressPath();
                    } else {
                        // 原图
                        path = media.getPath();
                    }
                    File file = new File(path);
                    //   文件上传
                    nameAttestationPresenter.shangchuanweijian(file, "material/");
                }


                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }


    @Override
    public void setPresenter(Contract.BasePresenter basePresenter) {

    }

    @Override
    public void onDataSucess(Object o){
        if(o instanceof NameAtteastationtpBean){
            tupianzhuangtai=true;
            NameAtteastationtpBean nameAtteastationtpBean= (NameAtteastationtpBean) o;
            String data = nameAtteastationtpBean.getData();
            if(!TextUtils.isEmpty(data)){
                String aa= Constants.TP_URL+data;

                if(zhemiantype){
                    zhaopianzhengmian=aa;
                    Glide.with(this)
                            .load(aa)
                            .apply(RequestOptions.bitmapTransform(new RoundedCorners(20)))//圆角半径
                            .into(zhengmian);



                }else if(fanmiantype){
                    zhaopianfanmian=aa;
                    Glide.with(this)
                            .load(aa)
                            .apply(RequestOptions.bitmapTransform(new RoundedCorners(20)))//圆角半径
                            .into(fanmian);
                }
            }
            zhemiantype=true;
            fanmiantype=true;

        }else if(o instanceof ShimingRzCBean){
            ShimingRzCBean shimingRzCBean= (ShimingRzCBean) o;
            if(shimingRzCBean.getCode()==1000){

                if(shimingRzCBean.getData().getState().equals("2")){
                    String name = shimingRzCBean.getData().getName();
                    String idCard = shimingRzCBean.getData().getIdCard();
                    String enname = "*" + name.substring(1);
                    String ensf= idCard.substring(0,1) + "*****************" + idCard.substring(17);
                    mingzi.setText(enname);
                    shenfenhao.setText(ensf);
                    scrollview.setVisibility(View.GONE);
                    yijingrenzheng.setVisibility(View.VISIBLE);

                }else if(shimingRzCBean.getData().getState().equals("1")){


                    yijingrenzheng.setVisibility(View.GONE);
                    scrollview.setVisibility(View.VISIBLE);
                    ToastUtils.show(NameAttestationActivity.this,"正在审核中");

                }else {
                    yijingrenzheng.setVisibility(View.GONE);
                    scrollview.setVisibility(View.VISIBLE);

                }
            }else {
                ToastUtils.show(NameAttestationActivity.this,shimingRzCBean.getMessage());
            }
        }else if(o instanceof NameattestationBean){
            NameattestationBean nameattestationBean= (NameattestationBean) o;
            if(nameattestationBean.getCode()==1000){
                ToastUtils.show(NameAttestationActivity.this,nameattestationBean.getMessage());
                finish();
            }else {
                ToastUtils.show(NameAttestationActivity.this,nameattestationBean.getMessage());
            }

        }

    }

    @Override
    public void onDataFaile(Object o) {

    }

    @Override
    public void onComplete() {

    }
}
